package controller

import (
	"test/gincircl/common"
	"test/gincircl/kyber"

	"github.com/gin-gonic/gin"
)

func KyberGenKeyPair(c *gin.Context) {
	var params common.KyberGen
	common.Logger.Info(c.Request.URL.Path)
	err := c.ShouldBindJSON(&params)
	if err != nil {
		common.Logger.Error("解析参数错误" + err.Error())
		common.FailWithMessage("解析参数错误", c)
		return
	}
	kyber, err := kyber.NewKyber(params.Type)
	if err != nil {
		common.Logger.Error("参数错误" + err.Error())
		common.FailWithDetailed(err.Error(), "参数错误", c)
		return
	}
	pk, prik, err := kyber.GenerateKeyPair()
	if err != nil {
		common.Logger.Error("生成密钥对失败" + err.Error())
		common.FailWithDetailed(err.Error(), "生成密钥对失败", c)
		return
	}
	common.OkWithData(map[string]interface{}{
		"pk": pk,
		"sk": prik,
	}, c)
}

func KyberEncapsulate(c *gin.Context) {
	common.Logger.Info(c.Request.URL.Path)
	var params common.KyberEncapsulate
	err := c.ShouldBindJSON(&params)
	if err != nil {
		common.Logger.Error("解析参数错误" + err.Error())
		common.FailWithMessage("解析参数错误", c)
		return
	}
	kyber, err := kyber.NewKyber(params.Type)
	if err != nil {
		common.Logger.Error("参数错误" + err.Error())
		common.FailWithDetailed(err.Error(), "参数错误", c)
		return
	}
	pk, prik, err := kyber.Encapsulate(params.PK)
	if err != nil {
		common.Logger.Error("密钥封装失败" + err.Error())
		common.FailWithDetailed(err.Error(), "密钥封装失败", c)
		return
	}
	common.OkWithData(map[string]interface{}{
		"ciphertext": pk,
		"sharedkey":  prik,
	}, c)
}

func KyberDecapsulate(c *gin.Context) {
	common.Logger.Info(c.Request.URL.Path)
	var params common.KyberDecapsulate
	err := c.ShouldBindJSON(&params)
	if err != nil {
		common.Logger.Error("解析参数错误" + err.Error())
		common.FailWithMessage("解析参数错误", c)
		return
	}
	kyber, err := kyber.NewKyber(params.Type)
	if err != nil {
		common.Logger.Error("参数错误" + err.Error())
		common.FailWithDetailed(err.Error(), "参数错误", c)
		return
	}
	pk, err := kyber.Decapsulate(params.SK, params.Cipher)
	if err != nil {
		common.Logger.Error("密钥解封装失败" + err.Error())
		common.FailWithDetailed(err.Error(), "密钥解封装失败", c)
		return
	}
	common.OkWithData(map[string]interface{}{
		"sharedkey": pk,
	}, c)
}
